<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2018/7/13
 * Time: 12:13
 */
namespace PddWechat\Library;


use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;
use Dai\Framework\Base\BaseException;
use Dai\Framework\Library\ConfigLibrary;
use Dai\Framework\Library\RedisExt;

Config::load();

class SmsLibrary {

    static $acsClient = null;
    const timeLimit = 240;
    const codeTime = 300;
    private static $basicConfig;

    public function __construct()
    {
        self::$basicConfig = ConfigLibrary::get("sms","basic");
    }

    /**
     * 取得AcsClient
     * @return DefaultAcsClient
     */

    public static function getAcsClient() {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";
        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";
        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = self::$basicConfig->accessKeyId; // AccessKeyId
        $accessKeySecret = self::$basicConfig->accessKeySecret; // AccessKeySecret
        // 暂时不支持多Region
        $region = "cn-hangzhou";
        // 服务结点
        $endPointName = "cn-hangzhou";
        if(static::$acsClient == null) {
            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    public static function sendSms($phone,$code,$serial)
    {
        if(RedisExt::getInstance()->exists($phone)) {
            if(RedisExt::getInstance()->ttl($phone) > self::timeLimit) {
                throw new BaseException(BaseException::SMS_SEND_FAILED);
            }
        }
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();
        // 必填，设置短信接收号码
        $request->setPhoneNumbers($phone);
        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName(self::$basicConfig->signName);
        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode(self::$basicConfig->templateCode);
        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code"=>$code,
            "product"=>"dsd"
        ), JSON_UNESCAPED_UNICODE));
        // 可选，设置流水号
        $request->setOutId($serial);
        // 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
        $request->setSmsUpExtendCode("1234567");

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);
        if($acsResponse->Message == "OK" && $acsResponse->Code == "OK") {
            $res = self::saveCodeToRedis($phone,$code);
            if(!$res){
                throw new BaseException(BaseException::SMS_SEND_FAILED);
            }
        }else{
            throw new BaseException(BaseException::SMS_SEND_FAILED);
        }
        return $acsResponse;
    }

    public static function makeCode() {
        $code = "";
        for($i=0;$i<4;$i++){
            $code .= rand(0,9);
        }
        return $code;
    }

    /**
     * 生成流水号
     * @return float
     */
    public static function makeSerialNumber() {
        list($usec, $sec) = explode(" ", microtime());
        $time = (float)$usec + (float)$sec;
        return $time;
    }

    public static function saveCodeToRedis($phone, $code) {;
        $res = RedisExt::getInstance()->set($phone,$code,self::codeTime);
        return $res;
    }

    public static function getCode($phone) {
        return RedisExt::getInstance()->get($phone);
    }
}